package com.llkj.qingnianguoxue.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.MainActivity;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.HomeModuleAdapter;
import com.llkj.qingnianguoxue.adapter.WorksAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.EventChangeUserBean;
import com.llkj.qingnianguoxue.bean.HomeModuleBean;
import com.llkj.qingnianguoxue.bean.UserIndexBean;
import com.llkj.qingnianguoxue.bean.WorkListBean;
import com.llkj.qingnianguoxue.circle.WorkListActivity;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.mine.mycoin.MyScoreActivity;
import com.llkj.qingnianguoxue.mine.mycourse.StudentCourseActivity;
import com.llkj.qingnianguoxue.mine.mycourse.TeacherCourseActivity;
import com.llkj.qingnianguoxue.music.RecordCompleteActivity;
import com.llkj.qingnianguoxue.util.GridSpacingItemDecoration;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 我的
 */
public class MineFragment extends BaseFragment implements View.OnClickListener/*, SwipeRefreshLayout.OnRefreshListener*/ {
    private static final int REQUEST_CODE = 6789;
    private static final int REQUEST_MODIFY_SIGNATURE = 6790;

    @BindView(R.id.tv_new_msg)
    TextView tvNewMsg;
    //    @BindView(R.id.swipeRefreshLayout)
//    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.ll_head)
    LinearLayout llHead;//头像
    @BindView(R.id.iv_head)
    ImageView ivHead;//头像
    @BindView(R.id.tv_name)
    TextView tvName;//名字
    @BindView(R.id.tvSignature)
    TextView tvSignature;//个性签名
    @BindView(R.id.tv_time_long)
    TextView tvTimeLong;//学习时间
    @BindView(R.id.tv_study_count)
    TextView tvStudyCount;//学习次数
    @BindView(R.id.tv_day_count)
    TextView tvDayCount;//学习时长

    @BindView(R.id.rlWorkRoot)
    RelativeLayout rlWorkRoot;
    @BindView(R.id.rlWorks)
    RecyclerView mRlWorks;//作品
    private WorksAdapter mWorkAdapter;
    private List<WorkListBean> mWorksData;

    @BindView(R.id.rv_module)
    RecyclerView mLvModule;//选项
    private HomeModuleAdapter moduleAdapter;
    private List<HomeModuleBean> moduleData;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_mine, container, false);
        setTitle("我的", false, -1, -1, true, TITLE_TYPE_IMG, R.drawable.icon_mine_msg);
        ButterKnife.bind(this, rootView);
        EventBus.getDefault().register(this);

        initView();
        initData();
        initListener();

        getUserData();
        return rootView;
    }

    private void initView() {
        tvTitle.setTextColor(ContextCompat.getColor(getContext(), R.color.white));
        rlTitle.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorFE4A49));
        titleLineBottom.setVisibility(View.GONE);
//        refreshLayout.setColorSchemeResources(R.color.blue3989ff);

        GridLayoutManager mgr = new GridLayoutManager(getActivity(), 4);
        mLvModule.setLayoutManager(mgr);
        //设置每个item间距
        mLvModule.addItemDecoration(new GridSpacingItemDecoration(4, 10, false));
        //子功能
        initModule();
        moduleAdapter = new HomeModuleAdapter(R.layout.item_home_module, moduleData);
        mLvModule.setAdapter(moduleAdapter);
    }

    private void initData() {
        mRlWorks.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        mWorksData = new ArrayList<>();
        mWorkAdapter = new WorksAdapter(R.layout.item_owner_work, mWorksData);
        mRlWorks.setAdapter(mWorkAdapter);
    }

    private void initListener() {
//        refreshLayout.setOnRefreshListener(this);
        mRlWorks.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                WorkListBean item = mWorksData.get(i);
                Bundle bundle = new Bundle();
                bundle.putString("categoryType","1");
                bundle.putString("musicLrcUrl",item.getLyric());//歌词链接
                bundle.putString("recordPath",item.getSing());//录制文件地址
                bundle.putString("musicCoverUrl",item.getSing_img());//伴奏音乐封面图片
                bundle.putString("musicName",item.getName());//伴奏音乐名称
                bundle.putString("countSing",item.getPlay_num());//演唱人数
                bundle.putString("musicBgPath",item.getBg_img());//背景图片地址
                startActivity(RecordCompleteActivity.class,bundle);
            }
        });
        mLvModule.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Bundle bundle = null;
                switch (i) {
                    case 0://我的好友
                        startActivity(MyFriendsActivity.class);
                        break;
                    case 1://账户余额
                        startActivity(BalanceActivity.class);
                        break;
                    case 2://范儿币
                        startActivity(MyScoreActivity.class);
                        break;
                    case 3://直播预约
                        ToastUtil.makeLongText(getActivity(), "对不起，暂未开通该功能");
//                        startActivity(MyZhiBoActivity.class);
                        break;
                    case 4://我的课程
                        String identity = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_IDENTITY_TYPE);
                        //1 用户 2 老师
                        if ("2".equals(identity)) {
                            startActivity(TeacherCourseActivity.class);
                        } else {
                            startActivity(StudentCourseActivity.class);
                        }

                        break;
                    case 5://我的收藏
                        startActivity(MyCollectionActivity.class);
                        break;
                    case 6://我的评论
                        bundle = new Bundle();
                        bundle.putInt("from_class", 2);
                        startActivity(MyPraiseActivity.class, bundle);
                        break;
                    case 7://我赞过的
                        bundle = new Bundle();
                        bundle.putInt("from_class", 1);
                        startActivity(MyPraiseActivity.class, bundle);
                        break;
                    case 8://我的活动
                        startActivity(MyActionsActivity.class);
                        break;
                    case 9://邀请好友
                        startActivity(InviteFriendActivity.class);
                        break;
                    case 10://账号
                        startActivity(AccountActivity.class);
                        break;
                    case 11://设置
                        startActivityForResult(SystemSettingActivity.class, new Bundle(), REQUEST_CODE);
                        break;
                    case 12://课程设置
                        startActivity(ClassroomSettingActivity.class);
                        break;
                }
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeUser(EventChangeUserBean event){
        HomeModuleBean moduleBean = moduleData.get(moduleData.size()-1);
        if ("2".equals(MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_IDENTITY_TYPE))) {
            if(!"课堂设置".equals(moduleBean.getTitle())){
                // 1 不是老师 2 是老师
                moduleBean = new HomeModuleBean();
                moduleBean.setPic(R.drawable.icon_mine_classroom_setting);
                moduleBean.setTitle("课堂设置");
                moduleData.add(moduleBean);
                moduleAdapter.notifyDataSetChanged();
            }
        }else{
            if("课堂设置".equals(moduleBean.getTitle())){
                moduleData.remove(moduleData.size()-1);
                moduleAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK && requestCode == REQUEST_MODIFY_SIGNATURE) {
            String signature = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_SIGNATURE);
            tvSignature.setText(signature);
        } else if (resultCode == getActivity().RESULT_OK) {
            ((MainActivity) getActivity()).setSelect(0);
        }
    }

    @Override
    protected void rightDoWhat() {
        super.rightDoWhat();
        startActivity(MessageActivity.class);
    }

    @OnClick({R.id.ll_head, R.id.rlWorkRoot, R.id.llSignature})
    public void onClick(View v) {
        Bundle bundle = null;
        switch (v.getId()) {
            case R.id.rlWorkRoot://查看作品
                String uid = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
                bundle = new Bundle();
                bundle.putString("uid", uid);
                startActivity(WorkListActivity.class, bundle);
                break;
            case R.id.ll_head://头像
                startActivity(PersonInfoActivity.class);
                break;
            case R.id.llSignature:
                bundle = new Bundle();
                startActivityForResult(ModifySignatureActivity.class, bundle, REQUEST_MODIFY_SIGNATURE);
                break;
//            case R.id.fr_shop_cart://购物车
//                startActivity(ShopCartActivity.class);
//                break;
//            case R.id.fr_bind_phone://绑定手机
//                startActivity(BindPhoneActivity.class);
//                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getUserData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        String headUrl = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_HEAD);
        ImageLoadingUtil.loadingCircleBorderImg(ivHead, headUrl, R.color.colorffffff);
        String name = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_NAME);
        tvName.setText(name);
        String signature = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_SIGNATURE);
        tvSignature.setText(signature);
        if (!StringUtils.isEmpty(signature)) {
            tvSignature.setHint("");
        }
        setNewMsgVisible();
    }

    /**
     * 获取8.3我的信息
     */
    private void getUserData() {
        HttpMethod.userIndex(getActivity(), this);
//        String uid = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
//        String token = MyApplication.getInstance().sputil.getString(ConstantUserInfo.TOKEN);
//        HttpMethod.kojiSing(getActivity(),this,uid,token,String.valueOf(1));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
//        refreshLayout.setRefreshing(false);
        if (method == HttpMethod.HTTP_USER_INDEX) {
            UserIndexBean userBean = GsonUtil.GsonToBean(data, UserIndexBean.class);
            if (userBean != null && userBean.getUser() != null) {
                UserIndexBean.UserBean user = userBean.getUser();
                ImageLoadingUtil.loadingCircleBorderImg(ivHead, user.getUserpic(), R.color.colorffffff);
                tvName.setText(user.getUsername());

                if (!StringUtils.isEmpty(user.getStudy_time())) {
                    tvTimeLong.setText(user.getStudy_time());
                }
                tvStudyCount.setText(user.getStudy_num() + "次");
                tvDayCount.setText(user.getContinuous() + "天");

                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_HEAD, user.getUserpic());
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_NAME, user.getUsername());
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_SEX, user.getSex());//性別1 男 2 女3 保密
                MyApplication.getInstance().sputil.put(ConstantUserInfo.INVITATION_CODE, user.getInvitation());//邀请码
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_EDUCATION, user.getEducation());//学历
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_BIRTHDAY, user.getBirthday());//生日
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_INDUSTRY, user.getIndustry());//行业
                MyApplication.getInstance().sputil.put(ConstantUserInfo.IS_PUSH, user.getIs_push());//推送1是 2否
                MyApplication.getInstance().sputil.put(ConstantUserInfo.IS_MOBILE, user.getMobile());//1 否 2绑定过手机号
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_BALANCE, user.getBalance());//余额
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_INTEGRAL, user.getIntegral());//积分
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_SIGNATURE, user.getSignature());//个性签名
            }

            if (userBean != null && userBean.getKoji() != null && userBean.getKoji().size() > 0) {
                int size = userBean.getKoji().size();
                size = size > 3 ? 3 : size;
                mWorksData.clear();
                mWorksData.addAll(userBean.getKoji().subList(0, size));
                mWorkAdapter.notifyDataSetChanged();
                rlWorkRoot.setVisibility(View.VISIBLE);
            } else {
                rlWorkRoot.setVisibility(View.GONE);
            }
            try {
                int mum = Integer.parseInt(userBean.getMessage_num());//未读消息
                MyApplication.getInstance().sputil.put(ConstantUserInfo.IS_NEW_SYS_MSG, mum);

                setNewMsgVisible();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        else if (HttpMethod.HTTP_KOJI_SING == method) {//
//            ResponseList<WorkListBean> response = GsonUtil.fromJsonList(data,WorkListBean.class);
//            if(response!=null){
//                mWorksData.clear();
//                if(response.getLike()!=null){
//                    int size = response.getLike().size();
//                    size = size>3?3:size;
//                    mWorksData.addAll(response.getLike().subList(0,size));
//                    mWorkAdapter.notifyDataSetChanged();
//                }
//            }
//        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
//        refreshLayout.setRefreshing(false);
        if (StringUtils.isEmpty(message)) {
            ToastUtil.makeLongText(getActivity(), message);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    public void setNewMsgVisible() {
        String mUserId = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
        int num = MyApplication.getInstance().sputil.getInt(ConstantUserInfo.IS_NEW_SYS_MSG);
        boolean istrue = num > 0 ? true : false;
        if (istrue) {
            tvNewMsg.setVisibility(View.VISIBLE);
        } else {
            tvNewMsg.setVisibility(View.INVISIBLE);
        }
    }

//    @Override
//    public void onRefresh() {
//        getUserData();
//    }

    private void initModule() {
        moduleData = new ArrayList<>();
        HomeModuleBean moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_friend);
        moduleBean.setTitle("我的好友");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_balance);
        moduleBean.setTitle("账户余额");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_coin);
        moduleBean.setTitle("范儿币");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_book);
        moduleBean.setTitle("直播预约");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_course);
        moduleBean.setTitle("我的课程");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_save);
        moduleBean.setTitle("我的收藏");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_comment);
        moduleBean.setTitle("我的评论");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_praise);
        moduleBean.setTitle("我赞过的");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_actions);
        moduleBean.setTitle("我的活动");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_invite);
        moduleBean.setTitle("邀请好友");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_account);
        moduleBean.setTitle("账号");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_mine_setting);
        moduleBean.setTitle("设置");
        moduleData.add(moduleBean);
        if ("2".equals(MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_IDENTITY_TYPE))) {
            // 1 不是老师 2 是老师
            moduleBean = new HomeModuleBean();
            moduleBean.setPic(R.drawable.icon_mine_classroom_setting);
            moduleBean.setTitle("课堂设置");
            moduleData.add(moduleBean);
        }
    }
}
